<script setup>
import { computed, ref, watch, nextTick, unref } from "vue";
import epIcons from "./data/icons.ep";
import antIcons from "./data/icons.ant-design";
import tIcons from "./data/icons.tdesign";
import { useAppStore } from "@/store/modules/app";
import { useDesign } from "@/hooks/web/useDesign";

// 👉 props + emits：支持 v-model
const props = defineProps({
  modelValue: String,
  defaultValue: { type: String, default: "" },
});
const emit = defineEmits(["update:modelValue"]);

// 👉 v-model 响应式处理
const currentValue = ref(props.modelValue || props.defaultValue);
watch(
  () => props.modelValue,
  (val) => (currentValue.value = val)
);
watch(
  () => currentValue.value,
  (val) => emit("update:modelValue", val)
);

// 👉 搜索 & 图标分页逻辑
const appStore = useAppStore();
const size = computed(() => appStore.getCurrentSize);
const iconSize = computed(() => {
  const s = unref(size);
  if (s === "small") return "var(--el-component-size-small)";
  if (s === "large") return "var(--el-component-size-large)";
  return "var(--el-component-size)";
});

const { getPrefixCls } = useDesign();
const prefixCls = getPrefixCls("icon-picker");

const icons = [epIcons, antIcons, tIcons];
const iconName = ref(icons[0].prefix);
const search = ref("");
const currentPage = ref(1);
const pageSize = ref(49);

const currentIconNameIndex = computed(() =>
  icons.findIndex((item) => item.prefix === unref(iconName))
);

function filterItemIcons(iconList) {
  const searchVal = unref(search);
  return iconList.filter((icon) => icon.includes(searchVal));
}

function filterIcons(iconList) {
  const start = (unref(currentPage) - 1) * unref(pageSize);
  const end = unref(currentPage) * unref(pageSize);
  return iconList.slice(start, end);
}

function iconSelect(icon) {
  if (icon === currentValue.value) {
    currentValue.value = "";
  } else {
    currentValue.value = icon;
  }
}

async function init(icon) {
  if (!icon) return;
  const iconInfo = icon.split(":");
  iconName.value = iconInfo[0];

  const wrapIndex = icons.findIndex((item) => item.prefix === iconInfo[0]);
  if (wrapIndex === -1) {
    console.warn(`[IconPicker] 无效的 icon 前缀：${iconInfo[0]}`);
    return;
  }

  const filteredIcons = filterItemIcons(icons[wrapIndex].icons);
  const index = filteredIcons.findIndex((item) => item === icon);

  await nextTick();
  currentPage.value = Math.ceil((index + 1) / unref(pageSize));
}

watch(
  () => currentValue.value,
  (val) => val && init(val),
  { immediate: true }
);

function inputClear() {
  init(currentValue.value);
}

function tabChange() {
  currentPage.value = 1;
}

function popoverShow() {
  init(currentValue.value);
}

const iconWrapStyle = computed(() => ({
  width: unref(iconSize),
  height: unref(iconSize),
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  boxShadow:
    "0 0 0 1px var(--el-input-border-color,var(--el-border-color)) inset",
  position: "relative",
  left: "-1px",
  cursor: "pointer",
}));
</script>

<template>
  <div :class="prefixCls" class="flex justify-center items-center box">
    <ElInput disabled v-model="currentValue" clearable />{{ currentValue }}
    <ElPopover
      placement="bottom"
      trigger="click"
      :width="450"
      popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; height: 380px;"
      @show="popoverShow"
    >
      <template #reference>
        <div :style="iconWrapStyle">
          <Icon v-if="currentValue" :icon="currentValue" />
        </div>
      </template>

      <ElScrollbar class="h-[calc(100%-50px)]!">
        <ElInput
          v-model="search"
          class="mb-20px"
          clearable
          placeholder="搜索图标"
          @clear="inputClear"
        />

        <ElTabs tab-position="left" v-model="iconName" @tab-change="tabChange">
          <ElTabPane
            v-for="item in icons"
            :key="item.name"
            :label="item.name"
            :name="item.prefix"
          >
            <div class="flex flex-wrap box-border">
              <div
                v-for="icon in filterIcons(filterItemIcons(item.icons))"
                :key="icon"
                :style="{
                  width: iconSize,
                  height: iconSize,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                  border: `1px solid ${
                    icon === currentValue
                      ? 'var(--el-color-primary)'
                      : 'var(--el-border-color)'
                  }`,
                  boxSizing: 'border-box',
                  margin: '2px',
                  transition: 'all 0.3s',
                }"
                class="hover:border-color-[var(--el-color-primary)]!"
                @click="iconSelect(icon)"
              >
                <Icon
                  :icon="icon"
                  :color="
                    icon === currentValue
                      ? 'var(--el-color-primary)'
                      : 'inherit'
                  "
                />
              </div>
            </div>
          </ElTabPane>
        </ElTabs>
      </ElScrollbar>

      <div
        class="h-50px absolute bottom-0 left-0 flex items-center pl-[var(--el-popover-padding)] pr-[var(--el-popover-padding)]"
      >
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :pager-count="5"
          size="small"
          :page-sizes="[100, 200, 300, 400]"
          layout="total, prev, pager, next, jumper"
          :total="
            icons[currentIconNameIndex]?.icons
              ? filterItemIcons(icons[currentIconNameIndex].icons).length
              : 0
          "
        />
      </div>
    </ElPopover>
  </div>
</template>

<style scoped lang="less">
@prefix-cls: ~"@{adminNamespace}-icon-picker";

.@{prefix-cls} {
  :deep(.@{elNamespace}-input__wrapper) {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }
}
</style>
